<?php
namespace app\merchant\controller;
use think\Config;
use think\Db;
class Order extends Init{
    function _initialize(){
        parent::_initialize();
    }

    public function orderList(){
        if($this->request->isPost()){
            $page = input('post.page');
            $limit = input('post.limit');
            $store_id = session('store_id');
            $where = "o.store_id = {$store_id}";
            $order_sn = input('post.order_sn');
            if($order_sn){
                $where .= " AND o.order_sn LIKE '%{$order_sn}%'";
            }
            $user_name = input('post.user_name');
            if($user_name){
                $where .= " AND u.name LIKE '%{$user_name}%'";
            }
            $phone = input('post.phone');
            if($phone){
                $where .= " AND o.phone LIKE '%{$phone}%'";
            }
            $order_status = input('post.order_status');
            if($order_status){
                if($order_status != 1000){
                   $where .= " AND o.order_status = {$order_status}";
                }else{
                   $where .= " AND o.order_status = 0";
                }
            }
            $date_start = input('post.date_start');
            if($date_start){
                $where .= " AND o.add_time >=".strtotime($date_start);
            }
            $date_end = input('post.date_end');
            if($date_end){
                $where .= " AND o.add_time <=".strtotime($date_end);
            }
            $order_list = db('order')->alias('o')
                                     ->field('o.*,u.name as user_name,u.phone as user_phone')
                                     ->join('user u','o.user_id = u.user_id','LEFT')
                                     ->where($where)
                                     ->order('o.add_time desc')
                                     ->page($page,$limit)
                                     ->select();
            // echo db('order')->getLastSql();die;
            $count = db('order')->alias('o')
                                ->join('user u','o.user_id = u.user_id','LEFT')
                                ->where($where)
                                ->count();
            foreach($order_list as $key=>$value){
                if($value['order_status'] == 0){$order_list[$key]['order_status'] = '未付款';}
                elseif($value['order_status'] == 1){$order_list[$key]['order_status'] = '已付款';}
                elseif($value['order_status'] == 2){$order_list[$key]['order_status'] = '已发货';}
                elseif($value['order_status'] == 3){$order_list[$key]['order_status'] = '已完成';}
                elseif($value['order_status'] == 4){$order_list[$key]['order_status'] = '已取消';}

                //20180911新加---ws
                elseif($value['order_status'] == 5){$order_list[$key]['order_status'] = '归还中';}
                elseif($value['order_status'] == 6){$order_list[$key]['order_status'] = '店铺已收货';}
                elseif($value['order_status'] == 7){$order_list[$key]['order_status'] = '已验收';}
                elseif($value['order_status'] == 8){$order_list[$key]['order_status'] = '待用户确认';}
                elseif($value['order_status'] == 9){$order_list[$key]['order_status'] = '待用户支付';}
                elseif($value['order_status'] == 10){$order_list[$key]['order_status'] = '租赁中';}


                if($value['order_type'] == 1){$order_list[$key]['order_type'] = '快递';}
                elseif($value['order_type'] == 2){$order_list[$key]['order_type'] = '自提';$order_list[$key]['sname']=$_SESSION['think']['admin_user']['name'];$order_list[$key]['sphone']=$_SESSION['think']['admin_user']['phone'];$order_list[$key]['saddress']=$_SESSION['think']['admin_user']['address']; }
                $order_list[$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);

                //新加20180913--ws
                if(!empty($value['lease_time'])){
                    $order_list[$key]['lease_time'] = date('Y-m-d',$value['lease_time']);
                }else{
                    $order_list[$key]['lease_time'] = '无';
                }
                if(!empty($value['lease_end_time'])){
                    $order_list[$key]['lease_end_time'] = date('Y-m-d',$value['lease_end_time']);
                }else{
                    $order_list[$key]['lease_end_time'] = '无';
                }
                if(!empty($value['confirm_time'])){
                    $order_list[$key]['confirm_time'] = date('Y-m-d',$value['confirm_time']);
                }else{
                    $order_list[$key]['confirm_time'] = '无';
                }


                $goods_info = db('order_goods')->alias('o')
                                               ->field('o.*,g.name as goods_name')
                                               ->join('goods g','o.goods_id = g.goods_id','LEFT')
                                               ->where("order_id = {$value['order_id']}")
                                               ->select();
                foreach($goods_info as $k=>$v){
                  $goods_info[$k]['code'] = explode(',',$v['code']);
                  foreach($goods_info[$k]['code'] as $c=>$vo){
                     if($goods_info[$k]['code'][$c] == ''){
                        unset($goods_info[$k]['code'][$c]);
                     }
                  }
                  if($goods_info[$k]['code']){
                     foreach($goods_info[$k]['code'] as $co=>$bar){
                        $goods_info[$k]['code'][$co] = db('code')->where("code_id = {$bar}")->value('barcodes');
                     }
                     $goods_info[$k]['code'] = implode(',',$goods_info[$k]['code']);
                  }
                }
                $order_list[$key]['goods'] = $goods_info;



                //新加20180912---ws
                if(!empty($value['order_business_sn']) && $value['type']==1){
                    $map['order_id'] = $value['order_id'];
                    $map['type']= 4;
                    $pay = db('order_pay')->where($map)->find();
                    if($pay){
                        $order_list[$key]['business_pay'] = 1;
                    }else{
                        $order_list[$key]['business_pay'] = 0;
                    }
                }else{
                    $order_list[$key]['business_pay'] = 0;
                }

            }

         return json(array('code'=>0,'msg'=>'获取成功','data'=>$order_list,'count'=>$count));
        }
        return $this->fetch();
    }

    public function orderInfo(){
        $order_id = input('get.id');
        $order_info = db('order')->where("order_id={$order_id}")->find();
        $user_info = db('user')->field('name,phone')->where("user_id={$order_info['user_id']}")->find();
        $order_info['user_name'] = $user_info['name'];
        $order_info['user_phone'] = $user_info['phone'];
        $goods_info = db('order_goods')->alias('o')
                                       ->field('o.*')
                                       ->where("order_id = {$order_id}")
                                       ->select();
        foreach($goods_info as $k=>$v){
          $goods_info[$k]['goods_name'] = db('goods')->where("goods_id = {$v['goods_id']}")->value('name');
          $goods_info[$k]['code'] = explode(',',$v['code']);
          foreach($goods_info[$k]['code'] as $c=>$vo){
             if($goods_info[$k]['code'][$c] == ''){
                unset($goods_info[$k]['code'][$c]);
             }
          }
          if($goods_info[$k]['code']){
             foreach($goods_info[$k]['code'] as $co=>$bar){
                $goods_info[$k]['code'][$co] = db('code')->where("code_id = {$bar}")->value('barcodes');
             }
             $goods_info[$k]['code'] = implode(',',$goods_info[$k]['code']);
          }
        }
        $order_info['goods'] = $goods_info;
        $order_info['add_time'] = date('Y-m-d H:i:s',$order_info['add_time']);
        $order_pay = db('order_pay')->where("order_id = {$order_id}")->find();
        $this->assign('list',$order_info);
        $this->assign('order_pay',$order_pay);
        return $this->fetch();
    }

    public function orderDetail(){
        $order_id = input('get.id');
        $order_info = db('order')->where("order_id={$order_id}")->find();
        $user_info = db('user')->field('name,phone')->where("user_id={$order_info['user_id']}")->find();
        $order_info['user_name'] = $user_info['name'];
        $order_info['user_phone'] = $user_info['phone'];
        $goods_info = db('order_goods')->alias('o')
                                       ->field('o.*,g.name as goods_name')
                                       ->join('goods g','o.goods_id = g.goods_id','LEFT')
                                       ->where("order_id = {$order_id}")
                                       ->select();
        $order_info['goods'] = $goods_info;
        $order_info['add_time'] = date('Y-m-d H:i:s',$order_info['add_time']);
        $order_info['goods_shipping'] = db('shipping')->select();
        // dump($order_info);die;
        $this->assign('order_info',$order_info);
        return $this->fetch();
    }

    public function changeStatus(){
        if($this->request->isPost()){
            $order_id = input('post.order_id');
            $order_type = input('post.order_type');
            $type = input('post.type');
            if($order_type == 1){
               $data = input('post.');
               if(empty($data['numbers'])){
                  return json(array('code'=>201,'msg'=>'请填写物流号'));
               }

               $data['order_status'] = 2;
               $data['shipping_time'] = time();
               $change_status = db('order')->where("order_id={$order_id}")->update($data);
               if($change_status){
                   $this->orderLog($order_id,'商家在'.date('Y-m-d H:i:s').'的时候发货了。',1,$_SESSION['think']['admin_user']['store_id']);
                  return json(array('code'=>200,'msg'=>'发货成功'));
               }else{
                  return json(array('code'=>201,'msg'=>'发货失败'));
               }
            }elseif($order_type == 2){

               if($type == 2 ){
                   $update_status = db('order')->where("order_id={$order_id}")->update(['order_status'=>3,'confirm_time'=>time(),'end_time'=>time()]);
                   if($update_status){
                       $this->orderLog($order_id,'商家在'.date('Y-m-d H:i:s').'的时候确认了自提单出货并完成。',1,$_SESSION['think']['admin_user']['store_id']);
                       return json(array('code'=>200,'msg'=>'自提单完成'));
                   }else{
                       return json(array('code'=>201,'msg'=>'确认失败'));
                   }
               }elseif($type == 1){
                   $update_status = db('order')->where("order_id={$order_id}")->update(['order_status'=>10,'lease_time'=>strtotime('tomorrow'),'confirm_time'=>time()]);
                   if($update_status){
                       $this->orderLog($order_id,'商家在'.date('Y-m-d H:i:s').'的时候确认了自提单出货。',1,$_SESSION['think']['admin_user']['store_id']);
                       return json(array('code'=>200,'msg'=>'自提单完成'));
                   }else{
                       return json(array('code'=>201,'msg'=>'确认失败'));
                   }
               }

            }
        }
    }


    //订单日志方法
    function orderLog($order_id,$conten,$type,$id){
        $data_log['order_id'] = $order_id;
        $data_log['content'] = $conten;
        $data_log['create_time'] = time();
        $data_log['type'] = $type;
        $data_log['u_id'] = $id;
        db('order_log')->insert($data_log);
    }



    //新加收货
    function collect(){
        $type = input('type');
        if($type==1){
            //$ru = db('order')->where('order_id',input('id'))->setField('order_status', 6);
            $ru = db('order')->where('order_id',input('id'))->update(['order_status'=>6,'lease_confirm_time'=>time()]);
        }else{
            $ru = db('order')->where('order_id',input('id'))->update(['order_status'=>6,'lease_end_time'=>time()]);
        }

        $data['order_id'] = input('id');
        $data['content'] = '商家收货';
        $data['create_time'] = time();
        $data['type'] = 1;
        $data['u_id'] = $_SESSION['think']['admin_user']['store_id'];
        db('order_log')->insert($data);

        if($ru){
            return json(array('code'=>200,'msg'=>'收货成功'));
        }else{
            return json(array('code'=>0,'msg'=>'收货失败'));
        }
    }




    //新加商品质检
    function quality (){
        if(request()->isPost()){
            $data = $this->request->post();

            //有磨损
            if($data['discount']==1){
                if(!empty($data['abrasion_img'])){
                    $data['abrasion_img'] = implode(",",$data['abrasion_img']);
                    $url = config('aliyun_oss.url');
                    $data['abrasion_img'] = str_replace($url."abrasion","/abrasion",$data['abrasion_img']);
                }
            }else{

                //没有磨损，看下是否有逾期
                $goodsorder = db('order')->field('order_sn,deposit_price,pay_price,overdue_number,user_id')->where("order_id={$data['order_id']}")->find();
                if((int)$data['discount']==0 && $goodsorder['overdue_number']==0){
                    Db::startTrans();
                    try{$d = $goodsorder['deposit_price']*100;
                        $d = (int)$d;
                        if($d!=0){
                            $pay = & load_wechat('Pay');
                            $out_refund_no = 'S'.generateOrderNum();
                            $goods_price = $goodsorder['pay_price']*100;
                            $refund_price = $data['refund_price']*100;

                            // 调用退款接口
                            $result = $pay->refund($goodsorder['order_sn'], 0, $out_refund_no,(int)$goods_price, (int)$refund_price, $op_user_id = null);
                            if($result==false)return json(array('code'=>0,'msg'=>'操作失败，退款失败，原因不明（微信退款报错）'));
                        }

                            $goods_code = db('order_goods')->where('order_id',$data['order_id'])->field('code,goods_number,goods_id,spec_item,deposit')->select();
                            $deposit = 0;
                            foreach ($goods_code as $itme){
                                $where['goods_id'] = $itme['goods_id'];
                                $where['price_key'] = $itme['spec_item'];
                                db('spec_goods_price')->where($where)->setInc('store', $itme['goods_number']);
                                if(!empty($itme['code'])){
                                    $goods_code_id = explode(",",$itme['code']);
                                    foreach ($goods_code_id as $val){
                                        db('code')->where('code_id',$val)->setField('state', 0);
                                    }
                                }
                                $deposit += $itme['deposit'];
                            }

                            //查询免押额度
//                            $list = Db::name("config")->where("type='d'")->select();
//                            foreach ($list as $rs){
//                                $config[$rs['name']] = $rs['value'];
//                            }
                            $deposit = $deposit-$goodsorder['deposit_price'];
                            //查询用户的免押金额和信用
//                            $user_jd = db('user')->field('jd_integral,quota')->where("user_id={$goodsorder['user_id']}")->find();
//                            if((int)$user_jd['jd_integral']>=(int)$config['js_integral'] && (int)$user_jd['quota']>=(int)$config['mortgage']){
                                Db::name('user')->where('user_id', $goodsorder['user_id'])->setInc('available_integral', $deposit);
                                Db::name('user')->where('user_id', $goodsorder['user_id'])->setDec('frozen_integral',$deposit);
//                            }


                        //改状态
                            db('order')->where('order_id', $data['order_id'])->update(['order_status'=> 3,'business_confirm_time'=>time(),'end_time'=>time(),'refund_price'=>$data['refund_price'],'abrasion_price'=>0,'abrasion_explain'=>0,'abrasion_img'=>0]);

                            $data_log['order_id'] = $data['order_id'];
                            $data_log['content'] = '商家确认无误，退款金额'.$data['refund_price'];
                            $data_log['create_time'] = time();
                            $data_log['type'] = 1;
                            $data_log['u_id'] = $_SESSION['think']['admin_user']['store_id'];
                            db('order_log')->insert($data_log);

                        Db::commit();
                    }catch(\Exception $e){
                        Db::rollback();
                        return json(['code' => 0,'msg' => '操作失败，退款失败，原因不明']);
                    }
                    return json(array('code'=>200,'msg'=>'操作成功，退款成功'));
                }else{
                //有逾期
                    $data['abrasion_explain'] = 0;
                    $data['abrasion_img'] = 0;
                    $data['abrasion_price'] = 0;
                    //$data['business_payment_pay'] = 0;
                }
            }

            if($data['business_payment_pay']>$data['refund_price']){
                $data['refund_price'] = 0;
                $data['order_status'] = 9;
                $data_log['content'] = '商家编辑商品质检，等待用户确认支付，支付金额'.$data['business_payment_pay'];
            }elseif($data['business_payment_pay']<$data['refund_price']){
                $data['business_payment_pay'] = 0;
                $data['order_status'] = 8;
                $data_log['content'] = '商家编辑商品质检，等待用户确认，退款金额'.$data['refund_price'];
            }elseif($data['business_payment_pay']==$data['refund_price']){
                $data['business_payment_pay'] = 0;
                $data['order_status'] = 8;
                $data_log['content'] = '商家编辑商品质检，等待用户确认，退款金额'.$data['refund_price'];
            }

            unset($data['discount']);
            $result= db('order')->update($data);
            if($result){
                $data_log['order_id'] = $data['order_id'];
                $data_log['create_time'] = time();
                $data_log['type'] = 1;
                $data_log['u_id'] = $_SESSION['think']['admin_user']['store_id'];
                db('order_log')->insert($data_log);
                return json(array('code'=>200,'msg'=>'修改成功'));
            }else{
                return json(array('code'=>0,'msg'=>'修改失败'));
            }

        }




        $order = db('order')->alias('o')->join('je_user u','o.user_id=u.user_id')->where('o.order_id',input('id'))->field('o.*,u.name as uname,u.phone as uphone')->find();

        $order['goods'] = db('order_goods')->alias('g')->join('je_goods s','g.goods_id = s.goods_id')->field('g.*,s.name as sname')->where('order_id',input('id'))->select();
        $a = $order['overdue_number'];

        //实际应该退还时间
        if(!empty($a)){
             $order['sj'] = $order['lease_end_time']-($order['overdue_number']*86400);
        }

        $url = config('aliyun_oss.url');
        $order['abrasion_img'] = explode(",",str_replace("/abrasion",$url."abrasion",$order['abrasion_img']));

        if(!empty($order['overdue_number'])){
            $goodsrent = db('order_goods')->where('order_id',input('id'))->column('rent');
            $order['sum_price'] = array_sum($goodsrent);
        }else{
            $order['sum_price'] = 0;
        }

        return view('q',['order'=>$order]);
    }

    //查看订单信息
    function details(){
        $order = db('order')->alias('o')->join('je_user u','o.user_id=u.user_id')->where('o.order_id',input('id'))->field('o.*,u.name as uname,u.phone as uphone')->find();

        $order['goods'] = db('order_goods')->alias('g') ->join('je_goods s','g.goods_id = s.goods_id')->field('g.*,s.name as sname')->where('order_id',input('id'))->select();
        $a = $order['overdue_number'];

        $order['store'] = db('store')->where("store_id={$_SESSION['think']['admin_user']['store_id']}")->find();
        //实际应该退还时间
        if(!empty($a)){
            $order['sj'] = $order['lease_end_time']-($order['overdue_number']*86400);
        }

        $goodsrent = db('order_goods')->where('order_id',input('id'))->column('rent');
        $order['sum_price'] = array_sum($goodsrent);
        $url = config('aliyun_oss.url');

        $order['abrasion_img'] = explode(",",str_replace("/abrasion",$url."abrasion",$order['abrasion_img']));

        //减免费用
         $order['jmfy'] = $order['reduction_number']*$order['sum_price'];


        $order['log'] = db('order_log')->where('order_id',input('id'))->field('create_time,content,type,u_id')->select();
        foreach ($order['log'] as $key=>$val){
            if($val['type']==0){
                $order['log'][$key]['name'] = db('user')->where("user_id={$val['u_id']}")->value('name');
            }elseif($val['type']==1){
                $order['log'][$key]['name'] = db('store')->where("store_id={$val['u_id']}")->value('name');
            }elseif($val['type']==2){
                $order['log'][$key]['name'] = db('admin_user')->where("admin_user_id={$val['u_id']}")->value('name');
            }elseif($val['type']==3){
                $order['log'][$key]['name'] = '系统';
            }
        }


        return view('details',['order'=>$order]);
    }


}